package com.kidfruit.controller;

import com.alibaba.fastjson.JSON;
import com.kidfruit.model.TUser;
import com.kidfruit.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    @RequestMapping("/show")
    public String toIndex(HttpServletRequest request, Model model) {
        int userId = Integer.parseInt(request.getParameter("id"));
        TUser user = this.userService.getUserById(userId);
        model.addAttribute("user", user);
        //showUser reference to showUser.jsp
        return "showUser";
    }

    @RequestMapping(value = "/showUser")
    public ModelAndView show(HttpServletRequest request, @RequestParam(value = "id", required = true) int id) {
        System.out.println("/user/showUser....");
        TUser user = this.userService.getUserById(id);
        ModelAndView mv = new ModelAndView("showUser");
        mv.addObject("user", user);
        return mv;
    }

    @RequestMapping("/test")
    public ModelAndView test(HttpServletRequest request, @RequestParam(value = "id", required = true) int id) {
        ModelAndView mv = new ModelAndView(new MappingJackson2JsonView(), "idstring", id);
        return mv;
    }

    @RequestMapping("/userList")
    public ModelAndView showAll() {
        System.out.println("userList......");
        ModelAndView MV = new ModelAndView("userList.html");
        List<TUser> userList = userService.getAllUsers();
        System.out.println(JSON.toJSONString(userList));
        MV.addObject("userList", userList);


        return MV;
    }


    @RequestMapping(value = "/all", method = RequestMethod.GET)
    @ResponseBody
    public List<TUser> listAllUsers() {
        List<TUser> users = userService.getAllUsers();
        if (users.isEmpty()) {
            return null;
        }

        System.out.println(JSON.toJSONString(users));
        return users;
    }


    @RequestMapping("/angularjsTest")
    public ModelAndView angularjs(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("angularjsTest");
        return mv;
    }
}